/*

Properties passed from Drupal:
 
  ialSignupMessage
  ialNextLabel
  ialPrevLabel
  ialRegisterLabel
  ialLoginLabel

  ialRequestType      - type of request (manual, mail, interval) 
  ialInterval         - pause until auto requests
  ialCredential       - credential used to login (mail, name)
  ialRegisterUsername - Require username during registration

*/



var ialMailPattern = /^[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+@((?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+|(\[([0-9]{1,3}(\.[0-9]{1,3}){3}|[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})\]))$/;
var ialTimeout;



$(
  function(){ 
    ialInit();
  }
);


function ialInit(){

  switch(Drupal.settings.inline_ajax_login.ialRequestType){
    case 'mail': ialMailBehaviour(); break;
    case 'interval': ialIntervalBehaviour(); break;
    case 'manual': ialManualBehaviour(); break;
  }
  
  ialReset();
}



/* ---- Displays ---- */



function ialReset(){

  $('#inline-ajax-login .form-item').hide();
  $('#inline-ajax-login .form-submit').hide();
  $('#inline-ajax-login div.messages').remove();

  if (Drupal.settings.inline_ajax_login.ialCredential == 'mail'){
    $('#edit-inline-ajax-login-mail-wrapper').show();
  } else {
    $('#edit-inline-ajax-login-name-wrapper').show();
  }

  if (Drupal.settings.inline_ajax_login.ialRequestType == 'manual'){
    $('#edit-inline-ajax-login-request-submit').val(Drupal.settings.inline_ajax_login.ialNextLabel).show();
  }
}



function ialShowLogin(data){

  ialMessage(data['message']);
  ialErrors(data['errors']);

  if (Drupal.settings.inline_ajax_login.ialCredential == 'mail'){
    $('#edit-inline-ajax-login-mail-wrapper').show();
    $('#edit-inline-ajax-login-name-wrapper').hide();
  } else {
    $('#edit-inline-ajax-login-mail-wrapper').hide();
    $('#edit-inline-ajax-login-name-wrapper').show();
  }

  $('#edit-inline-ajax-login-request-submit').hide();
  $('#edit-inline-ajax-login-pass-again-wrapper').hide();
  $('#edit-inline-ajax-login-pass-wrapper, #edit-inline-ajax-login-request-previous').show();
  $('#edit-inline-ajax-login-submit')
    .val(Drupal.settings.inline_ajax_login.ialLoginLabel)
    .show()
    .unbind()
    .click(function(){ ialLogin(); return false; });
}



function ialShowRegister(data){

  ialMessage(
    '<div class="info message">' +
       Drupal.settings.inline_ajax_login.ialSignupMessage +
    '</div>' +
    (data ? data['message'] : '')
  );
  ialErrors(data ? data['errors'] : false);

  if (Drupal.settings.inline_ajax_login.ialRegisterUsername){
    $('#edit-inline-ajax-login-name-wrapper').show();
  }

  $('#edit-inline-ajax-login-request-submit').hide();
  $('#edit-inline-ajax-login-mail-wrapper, #edit-inline-ajax-login-pass-wrapper, #edit-inline-ajax-login-pass-again-wrapper, #edit-inline-ajax-login-request-previous').show();
  $('#edit-inline-ajax-login-submit')
    .val(Drupal.settings.inline_ajax_login.ialRegisterLabel)
    .show()
    .unbind()
    .click(function(){ ialRegister(); return false; });
}



function ialShowDone(message){
  $('#inline-ajax-login *:not(legend)').remove();
  ialMessage(message);
}



/* ---- Behaviours ---- */



function ialMailBehaviour(){

  var update = function(){

    clearTimeout(ialTimeout);

    if ($('#edit-inline-ajax-login-mail').val().match(ialMailPattern)){
      ialTimeout = setTimeout(
        'ialUserExists();', 
        Drupal.settings.inline_ajax_login.ialInterval
      );
    }
  }

  $('#edit-inline-ajax-login-mail').keyup(update);
}



function ialIntervalBehaviour(){

  var update = function(){
    clearTimeout(ialTimeout);
    ialTimeout = setTimeout('ialUserExists();', Drupal.settings.inline_ajax_login.ialInterval);
  }

  if (Drupal.settings.inline_ajax_login.ialCredential == 'mail'){
    $('#edit-inline-ajax-login-mail').keyup(update);
  } else {
    $('#edit-inline-ajax-login-name').keyup(update);
  }
}



function ialManualBehaviour(){

  $('#edit-inline-ajax-login-request-submit').click(
    function(){
      ialUserExists();
      return false;
    }
  );

  $('#edit-inline-ajax-login-request-previous').click(
    function(){
      ialReset(); 
      return false;
    }
  );
}



/* ---- Utilities ---- */



function ialMessage(message){

  var messageArea = $('#inline-ajax-login div.messages');
  var hasArea = $('#inline-ajax-login div.messages').length > 0;

  if (!message && hasArea){
    $('#inline-ajax-login div.messages').remove();
  }

  if (message){
    if (hasArea){
      messageArea.html(message);
    } else {
      $('#inline-ajax-login').prepend('<div class="messages">' + message + '</div>');
    }
  }
}



function ialErrors(errors){

  $('#inline-ajax-login .form-text').removeClass('error');

  if (errors){
    for (var index in errors){
      $('#edit-' + errors[index]).addClass('error');
    }
  }
}



function ialUpdateForm(data){
  if (data['form']){

    var type = $('form#node-form').attr('action').split('/').pop();

    var buildIdField = $("#node-form input[name='form_build_id']");
    buildIdField
      .attr('id', data['form']['id'])
      .attr('value', data['form']['id']);
      
    var tokenField = $("#node-form input[name='form_token']");
    if (tokenField.length){
      tokenField.attr('value', data['form']['token']);
    } else {
      $("#node-form").append('<input id="edit-' + type + '-node-form-form-token" name="form_token" type="hidden" value="' + data['form']['token'] + '" />');
    }

    if (data['form']['fields']){
      for (i = 0; i < data['form']['fields'].length; i++){
        var element = data['form']['fields'][i];
        $('#' + element['id']).replaceWith(element['html']);
      }
    }
  }
}



/* ---- Server requests ---- */



function ialUserExists(){

  $('#edit-inline-ajax-login-mail, #edit-inline-ajax-login-name').addClass('throbbing');

  var lookupVal = Drupal.settings.inline_ajax_login.ialCredential == 'mail'
    ? $('#edit-inline-ajax-login-mail').val()
    : $('#edit-inline-ajax-login-name').val();

  $.getJSON('/ial/ajax/user/exists/' + lookupVal, null, function(data, textStatus){
      if (data){
        ialShowLogin(data);
      } else {
        ialShowRegister(Array());
      }
      $('#edit-inline-ajax-login-mail, #edit-inline-ajax-login-name').removeClass('throbbing');
    }
  );

  return false;
}



function ialLogin(data){

  ialMessage();

  var type = $('form#node-form').attr('action').split('/').pop();

  var credential = Drupal.settings.inline_ajax_login.ialCredential == 'mail'
    ? ($('#edit-inline-ajax-login-mail').val() ? $('#edit-inline-ajax-login-mail').val() : 0)
    : ($('#edit-inline-ajax-login-name').val() ? $('#edit-inline-ajax-login-name').val() : 0);

  var pass = $('#edit-inline-ajax-login-pass').val() ? $('#edit-inline-ajax-login-pass').val() : 0;

  $.getJSON('/ial/ajax/user/login/' + credential + '/' + pass + '/' + type, null, function(data, textStatus){
      if (data){
        if (data['closeform']){
          ialShowDone(data['message']);
          ialUpdateForm(data);
        } else {
          ialShowLogin(data);
        }
      }
    }
  );
}



function ialRegister(){

  ialMessage();

  if ($('#edit-inline-ajax-login-pass').val() != $('#edit-inline-ajax-login-pass-again').val()){
    ialMessage('<div class="error message">' + Drupal.settings.inline_ajax_login.ialPassMismatchMessage + '</div>');
    $('#edit-inline-ajax-login-pass, #edit-inline-ajax-login-pass-again').addClass('error');
    return;
  }

  var type = $('form#node-form').attr('action').split('/').pop();

  var mail = $('#edit-inline-ajax-login-mail').val() ? $('#edit-inline-ajax-login-mail').val() : 0;
  var name = Drupal.settings.inline_ajax_login.ialRegisterUsername || Drupal.settings.inline_ajax_login.ialCredential == 'name'
    ? '/' + $('#edit-inline-ajax-login-name').val()
    : 0;
  var pass = $('#edit-inline-ajax-login-pass').val() ? $('#edit-inline-ajax-login-pass').val() : 0;

  $.getJSON('/ial/ajax/user/register/' + mail + '/' + pass + '/' + type + name, null, function(data, textStatus){
      if (data){
        if (data['closeform']){
          ialShowDone(data['message']);
          ialUpdateForm(data);
        } else {
          ialShowRegister(data);
        }
      }
    }
  );
}



